package com.student.xujiang.myallstudent.GsonAndJackson;

import android.util.Log;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xujiang on 2017/3/21.
 */

public class Test {

    static String TAG = Test.class.getSimpleName();

    private static School initScoolData(){
        School school = new School();
        school.setAddress("Nanjing");
        school.setName("NUPT");
        List<Student> list = new ArrayList<Student>();
        for(int i=0;i<3;i++){

            Student student = new Student();
            student.setAge(20+i);
            student.setId("1000"+i);
            student.setName("stu"+1);
            list.add(student);
        }
        school.setStudents(list);
        return school;
    }

    public static void testGson(){

        School school = initScoolData();
        Gson gson = new Gson();
        //将对象转化成json字符串
        String jsonString = gson.toJson(school);       //打印
        Log.i(TAG,"GSON="+jsonString);
        //将字符串转化成JSON对象
        School resultSchool = gson.fromJson(jsonString,School.class);

        //打印
        Log.i(TAG,resultSchool.getStudents().get(0).getName());

        //4 、发送消息
        EventBus.getDefault().post(new MessageEvent(jsonString,resultSchool));

    }

    public static void testJackson(){
        School school = initScoolData();

        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = "";
        //将对象转化成Json字符串
        try {
            jsonString = objectMapper.writeValueAsString(school);
            Log.i(TAG,jsonString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        School resultSchool = null;

        //将json字符串解析成java对象
        try {
            resultSchool = objectMapper.readValue(jsonString, School.class);
            Log.i(TAG,resultSchool.getStudents().get(0).getName());
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //4 、发送消息
        EventBus.getDefault().post(new MessageEvent(jsonString,resultSchool));


        /**
         * 使用Jackson，主要是使用writeValueAsString和readValue这两个方法。此外，Jackson的writeValue和readValue有很多种参数类型，适用于多中场合。
         *
         *http://jackson.codehaus.org/
         * */

    }

}
